package org.wlgzs.moyue.service.servicelmpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.wlgzs.moyue.dao.*;
import org.wlgzs.moyue.dao.BookDao;
import org.wlgzs.moyue.dao.BookLinkTypeDao;
import org.wlgzs.moyue.dao.BookListDao;
import org.wlgzs.moyue.dao.TypeDao;
import org.wlgzs.moyue.entity.*;
import org.wlgzs.moyue.service.*;
import org.wlgzs.moyue.util.IoUtil;
import org.wlgzs.moyue.util.Result;
import org.wlgzs.moyue.util.ResultCode;

import javax.persistence.criteria.*;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.Comparator.comparingLong;
import static java.util.stream.Collectors.toCollection;


@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookDao bookDao;
    @Autowired
    private BookListService bookListService;
    @Autowired
    private BookLinkTypeDao bookLinkTypeDao;
    @Autowired
    private TypeDao typeDao;
    @Autowired
    private BookService bookService;
    @Autowired
    private BookListDao bookListDao;
    @Autowired
    private ConsumeService consumeService;
    @Autowired
    private BookcaseDao bookcaseDao;
    @Autowired
    private BookLinkTypeService bookLinkTypeService;
    @Autowired
    private UserDao userDao;
    @Autowired
    protected BrowseService browseServicek;

    @Override
    public List<String> paragraphList(String path) throws FileNotFoundException {
        List<String> list = new ArrayList<String>();
        Scanner scanner = new Scanner(new FileInputStream(path));
        while (scanner.hasNext()) {
            String world = scanner.next();
            list.add(world);
        }
        return list;
    }

    @Override
    public List<Type> findtypeId(Long type) {
        List<Type> typeList = typeDao.findByTypeParentId((long) 0);
        return typeList;
    }

    @Override
    public List<Book> getBooksByType(long typeId) {
        List<Type> types = typeDao.findByTypeParentId(typeId);
        types.add(typeDao.findById(typeId).get());
        List<BookLinkType> bookLinkTypes = new ArrayList<>();
        for (int i = 0; i < types.size(); i++) {
            bookLinkTypes.addAll(bookLinkTypeDao.findBookLinkTypesByTypeId(types.get(i).getTypeId()));
        }
        List<Book> books = new ArrayList<>();
        for (int i = 0; i < bookLinkTypes.size(); i++) {
            books.add(bookDao.findById(bookLinkTypes.get(i).getBookId()).get());
        }
        return books;
    }

    @Override
    public Result getBookMessage(long bookId) {
        return new Result(ResultCode.SUCCESS, bookDao.findById(bookId).get());
    }

    @Cacheable(value = "rankBook", key = "1")
    @Override
    public List<Book> rankBook() {
        List<Book> bookList = bookDao.findAll();
        int bookClicks;
        int bookCollections;
        int bookRewards;
        int synthesize;//综合量
        Map<Long, Integer> bookMap = new HashMap<Long, Integer>();
        Map<Long, Integer> bookMap1 = new HashMap<Long, Integer>();
        for (Book book : bookList) {
            bookClicks = book.getBookClicks();
            bookCollections = book.getBookCollections();
            bookRewards = book.getBookRewards();
            synthesize = (int) (bookClicks * 0.1 + bookCollections * 0.3 + bookRewards * 0.6);
            bookMap.put(book.getBookId(), synthesize);
        }
        bookMap1 = mapSort(bookMap);
        List<Book> bookList1 = new ArrayList<>();
        Set<Long> set = bookMap1.keySet(); //得到所有key的集合key为排序后书的Id
        Book book = new Book();
        for (Long bookId : set
                ) {
            book = bookDao.findById(bookId).get();
            bookList1.add(book);
        }
        System.out.println("只执行一次");
        return bookList1;
    }

    @Override
    @CacheEvict(value = "rankBook", key = "1")
    public void removeRankBook() {

    }

    @Override
    public Map mapSort(Map unsortMap) {//对map中的书进行排序
        List list = new LinkedList(unsortMap.entrySet());
        // System.out.println("list:"+list);
        Collections.sort(list, new Comparator() {
            public int compare(Object o1, Object o2) {
                return ((Comparable) ((Map.Entry) (o2)).getValue())
                        .compareTo(((Map.Entry) (o1)).getValue());
            }
        });
        Map sortedMap = new LinkedHashMap();

        for (Iterator it = list.iterator(); it.hasNext(); ) {
            Map.Entry entry = (Map.Entry) it.next();
            sortedMap.put(entry.getKey(), entry.getValue());
        }
        return sortedMap;
    }

    @Override
    public Book getDefault(Book book) {
        book.setBookIsActivity(1);
        book.setBookIsReview(0);
        book.setBookIsEnd(0);
        book.setBookWordCount(0);
        book.setBookListCount(0);
        book.setBookClicks(0);
        book.setBookCollections(0);
        book.setBookRewards(0);
        book.setBookUpdateDate(new Date());
        return book;
    }

    @Override
    public ModelAndView getBookSByBookName(String pagestr, String fbookName, Model model) {
        int page;
        if (pagestr == null) page = 1;
        else page = Integer.parseInt(pagestr);
        Pageable pageable = new PageRequest(page - 1, 10);
        Specification<Book> specification = new Specification<Book>() {
            @Override
            public Predicate toPredicate(Root<Book> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Path bookName = root.get("bookName");
                return criteriaBuilder.like(bookName, fbookName);
            }
        };
        Page<Book> bookPage = bookDao.findAll(specification, pageable);
        model.addAttribute("page", bookPage.getNumber() + 1);
        model.addAttribute("pages", bookPage.getTotalElements());
        model.addAttribute("books", bookPage.getContent());
        model.addAttribute("bookName", fbookName);
        return new ModelAndView("");

    }

    @Override
    public Result getBooklist(long bookId) {
        Book book = bookDao.getOne(bookId);
        BookList bookList = new BookList(0, null, bookId, null, book.getBookListCount() + 1, 0, 0);
        return new Result(ResultCode.SUCCESS, bookList);
    }

    @Override
    public ModelAndView getBooksByTypeId(int page, int typeIdNum, Model model) {
        Pageable pageable = new PageRequest(page - 1, 10);
        Specification<BookLinkType> specification = new Specification<BookLinkType>() {
            @Override
            public Predicate toPredicate(Root<BookLinkType> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Path typeId = root.get("typeId");
                return criteriaBuilder.equal(typeId, typeIdNum);
            }
        };
        Page<BookLinkType> bookLinkTypePage = bookLinkTypeDao.findAll(specification, pageable);
        List<BookLinkType> bookLinkTypes = bookLinkTypePage.getContent();
        List<Book> books = this.getBooksByBookLinkTypes(bookLinkTypes);
        model.addAttribute("page", bookLinkTypePage.getNumber() + 1);
        List<Type> typeList = typeDao.findByTypeParentId((long) 0);
        model.addAttribute("pages", bookLinkTypePage.getTotalPages());
        model.addAttribute("books", books);
        model.addAttribute("typeId",typeIdNum);
        model.addAttribute("type", typeList);
        return new ModelAndView("allwork");

    }

    @Override
    public ModelAndView getAllBook(int page, Model model) {
        Pageable pageable = new PageRequest(page - 1, 10);
        Page<Book> bookPage = bookDao.findAll(pageable);
        model.addAttribute("page", bookPage.getNumber() + 1);
        model.addAttribute("pages", bookPage.getTotalPages());
        model.addAttribute("books", bookPage.getContent());
        return new ModelAndView("bookmanage");
    }

    @Override
    public Result addBook(MultipartFile file, Book bookold, int[] types) {
        IoUtil ioUtil = new IoUtil();
        bookold = new BookServiceImpl().getDefault(bookold);
        Book book = bookDao.save(bookold);
        //String imgUrl = "/upload/user/" + book.getBookId() + "/" + file.getOriginalFilename();
        //book.setBookCoverUrl(imgUrl);
       // bookDao.save(book);
        if (true) {
            bookLinkTypeService.addBookLinkType(book.getBookId(), types);
            return new Result(ResultCode.SUCCESS);
        } else return new Result(ResultCode.FAIL, "创建书籍失败！");
    }

    @Override
    public Result updateBook(Book book) {

        return null;
    }

    @Override
    public Result deleteBook(long bookId) {
        if (bookDao.existsById(bookId)) {
            bookDao.deleteById(bookId);
            new IoUtil().deleteFile("./upload/book/" + bookId);
            return new Result(ResultCode.SUCCESS);
        } else return new Result(ResultCode.FAIL, "删除失败，请重试！");
    }

    @Override
    public Result deleteBooks(long[] num) {
        for (long bookId : num) {
            if (bookDao.existsById(bookId)) bookDao.deleteById(bookId);
            new IoUtil().deleteFile("./upload/book/" + bookId);
        }
        return new Result(ResultCode.SUCCESS);
    }

    @Override
    public boolean writeBook(BookList bookList, String context) {
        IoUtil ioUtil = new IoUtil();
        BookServiceImpl bookService = new BookServiceImpl();
        bookList = ioUtil.saveBookList(bookList, context);
        Book book = ioUtil.appendBook(bookList, context);
        bookListDao.save(bookList);
        bookDao.save(book);
        return true;
    }

    @Override
    public Result uploadBook(MultipartFile bookfile, MultipartFile imgfile, Book book, User user, int[] types) {
        book.setAuthorId(user.getUserId());
        book.setAuthorName(user.getUserName());
        bookLinkTypeService.addBookLinkType(book.getBookId(), types);
        IoUtil ioUtil = new IoUtil();
        BookServiceImpl bookService = new BookServiceImpl();
        long n = bookDao.count();
        book = new BookServiceImpl().getDefault(book);
        Book book1 = bookDao.save(book);
        if (bookDao.count() == (n + 1)) {
            String bookUrl = "/upload/book/" + book.getBookId() + "/all/" + bookfile.getOriginalFilename();
            String imgUrl = "/upload/book/" + book.getBookId() + "/img/" + imgfile.getOriginalFilename();
            if (ioUtil.saveFile(bookfile, bookUrl) && ioUtil.saveFile(imgfile, imgUrl)) {
                book1.setBookUrl(bookUrl);
                book1.setBookCoverUrl(imgUrl);
                bookDao.save(book1);
                List<BookList> bookLists = ioUtil.analysis(book);
                for (int i = 0; i < bookLists.size(); i++) {
                    bookListDao.save(bookLists.get(i));
                }
                bookLinkTypeService.addBookLinkType(book.getBookId(), types);
                return new Result(ResultCode.SUCCESS);
            }
            return new Result(ResultCode.FAIL);
        }
        return new Result(ResultCode.FAIL);
    }

    @Override
    public List<Book> getBooksByBookLinkTypes(List<BookLinkType> bookLinkTypes) {
        List<Book> books = new ArrayList<>();
        for (BookLinkType bookLinkType : bookLinkTypes) {
            books.add(bookDao.getOne(bookLinkType.getBookId()));
        }
        return books;
    }
/*
@Override
    public String addFile(Book book) {
      String filePath = book.getBookId() + "/" + book.getBookName() + ".txt";
       File file = new File(filePath);
        file.mkdirs();
        if (file.exists()) return filePath;
        else return null;

    }
*/


    @Override
    public List<String> getKeyWord(String keyWord) { //进行模糊搜索
        List<Book> bookList = bookDao.findAllByBookNameContaining(keyWord);
        if (bookList == null) {
            return null;
        }
        List<String> keyWordList = new ArrayList<String>();
        if (bookList.size() <= 10) {
            for (Book book : bookList
                    ) {
                keyWordList.add(book.getBookName());
            }
        } else {
            Book book = new Book();
            for (int i = 0; i < 10; i++) {
                book = bookList.get(i);
                keyWordList.add(book.getBookName());
            }
        }
        return keyWordList;
    }

    @Override
    public List<Book> sub(int end, List<Book> list) {
        if (list.size() < end) {
            return list;
        } else {
            return list.subList(0, end - 1);
        }
    }

    @Cacheable(value = "Booksreward", key = "1")
    @Override
    public List<Book> getBooksreward() {
        return bookDao.findAllByOrderByBookRewardsDesc();
    }

    @Cacheable(value = "BooksClick", key = "1")
    @Override
    public List<Book> getBooksClick() {
        return bookDao.findAllByOrderByBookClicksDesc();
    }

    @Cacheable(value = "BooksCollections", key = "1")
    @Override
    public List<Book> getBooksCollections() {
        return bookDao.findAllByOrderByBookCollectionsDesc();
    }

    @CacheEvict(value = "Booksreward", key = "1")
    @Override
    public void removeBooksreward() {

    }

    @CacheEvict(value = "BooksClick", key = "1")
    @Override
    public void removeBooksClick() {

    }

    @CacheEvict(value = "BooksCollections", key = "1")
    @Override
    public void removeBooksCollections() {

    }

    @Override
    public void index(Model model, List<Book> ranBook, List<Book> Booksreward, List<Book> BooksClick, List<Book> BooksCollections) {   //进入首页要加载的数据
        Map<Integer, Book> bookMapClection = new HashMap<Integer, Book>();
        Map<Integer, Book> bookMapClick = new HashMap<Integer, Book>();
        List<Type> typeList = typeDao.findByTypeParentId((long) 0);
        for (int i = 2; i <= 10; i++) {
            bookMapClection.put(i, BooksCollections.get(i - 1));
            bookMapClick.put(i, BooksClick.get(i - 1));
        }
        model.addAttribute("firstclection", BooksCollections.get(0));
        model.addAttribute("firstclick", BooksClick.get(0));
        model.addAttribute("rankbook", sub(7, ranBook));
        model.addAttribute("rewardbook", sub(7, Booksreward));
        model.addAttribute("clectionbook", bookMapClection);
        model.addAttribute("clickbook", bookMapClick);
        model.addAttribute("rewardtwo", sub(3, Booksreward));
        model.addAttribute("clicktwo", sub(3, Booksreward));
        model.addAttribute("clectionfour", sub(5, BooksCollections));
        model.addAttribute("rewardfour", sub(5, Booksreward));
        model.addAttribute("clickfour", sub(5, BooksClick));
        model.addAttribute("rankfour", sub(5, ranBook));
        model.addAttribute("type", typeList);
    }

    @Override
    public void toIndex(Model model, List<Book> ranBook, List<Book> Booksreward, List<Book> BooksClick, List<Book> BooksCollections) {    //进入排行榜
        Map<Integer, Book> bookMapRank = new HashMap<Integer, Book>();
        Map<Integer, Book> bookMapReward = new HashMap<Integer, Book>();
        Map<Integer, Book> bookMapClicks = new HashMap<Integer, Book>();
        Map<Integer, Book> bookMapCollections = new HashMap<Integer, Book>();
        for (int i = 2; i <= 10; i++) {
            bookMapRank.put(i, ranBook.get(i - 1));
            bookMapReward.put(i, Booksreward.get(i - 1));
            bookMapClicks.put(i, BooksClick.get(i - 1));
            bookMapCollections.put(i, BooksCollections.get(i - 1));
        }
        model.addAttribute("firstclection", BooksCollections.get(0));
        model.addAttribute("firstclick", BooksClick.get(0));
        model.addAttribute("firstRewards", Booksreward.get(0));
        model.addAttribute("firstrank", ranBook.get(0));
        model.addAttribute("clectionbook", bookMapCollections);
        model.addAttribute("clickbook", bookMapClicks);
        model.addAttribute("Rewardsbook", bookMapReward);
        model.addAttribute("rankbook", bookMapRank);

    }

    @Override
    public ModelAndView chapterView(Model model, long bookId, int listorderId, HttpSession session) throws FileNotFoundException {
        BookList bookList = bookListDao.findByBookIdAndBookListOrder(bookId, listorderId);
        browseServicek.addBrowse(bookList.getBookListId(),session);//记录浏览记录
        User user = (User) session.getAttribute("user");
        boolean isBuyed = consumeService.isBuyed(bookList.getBookListId(), bookId, session);//判断用户是否买过此章节
        Book book = bookDao.findById(bookId).get();
        List<BookLinkType> bookLinkTypes = bookLinkTypeDao.findByBookId(bookId);
        Long typeId = (long) 0;
        for (BookLinkType bookLinkType : bookLinkTypes
                ) {
            Type type = typeDao.findById(bookLinkType.getTypeId()).get();
            Long fatherId = type.getTypeParentId();
            if (fatherId != -1 && fatherId != 0) {
                typeId = bookLinkType.getTypeId();
            }
        }
        Type type = typeDao.findById(typeId).get();
        String subtype = type.getTypeName();
        Long fatherId = type.getTypeParentId();
        Type type1 = typeDao.findById(fatherId).get();
        String parentType = type1.getTypeName();
        List<BookList> bookLists = bookListDao.findByBookIdOrderByBookListOrderAsc(bookId);
        int count = bookListDao.countByBookId(bookId);
        boolean isTrue = user == null && bookList.getBookListOrder() > 30;
        if (book.getBookIsContract() == 1) {
            if (isTrue || !isBuyed) {
                model.addAttribute("booklist", bookList);
                model.addAttribute("parentype", parentType);
                model.addAttribute("subtype", subtype);
                model.addAttribute("book", book);
                model.addAttribute("money", bookList.getChapterPrice());
                return new ModelAndView("vipread");
            }
        }


        model.addAttribute("bookLists", bookLists);
        model.addAttribute("freeRead", bookLists.get(0));
        model.addAttribute("parentype", parentType);
        model.addAttribute("lastchapter", listorderId - 1);
        if (listorderId + 1 <= count) {
            model.addAttribute("nextchapter", listorderId + 1);
        } else {
            model.addAttribute("nextchapter", 0);
        }
        model.addAttribute("subtype", subtype);
        model.addAttribute("book", book);
        List<String> paragraphList = new ArrayList<String>();

        //  String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();//获取资源路径
        // System.out.println(path);

        //   String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();//获取资源路径
        String path = System.getProperty("user.dir");
        System.out.println(path);
        String filePath = path + "/" + bookList.getBookListUrl();//获取章节url
        System.out.println(filePath);
        paragraphList = paragraphList(filePath);//获取章节内容段落集合
        model.addAttribute("paragraphlist", paragraphList);
        String chapterName = paragraphList.get(0);
        model.addAttribute("chapterName", chapterName);
        model.addAttribute("booklist", bookList);
        paragraphList.remove(0);
        return new ModelAndView("read");
    }

    @Override
    public void bookView(Model model, long bookId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user != null) {
            User currentUser = userDao.findById(user.getUserId()).get();
            model.addAttribute("account", currentUser.getUserRewards());
            if (currentUser.getRoleId().equals("2")) {
                model.addAttribute("isVIP", "尊敬的" + user.getUserName() + "初级VIP用户，我们将为你打八折进行收费");
            }
            if (currentUser.getRoleId().equals("3")) {
                model.addAttribute("isVIP", "尊敬的" + user.getUserName() + "高级VIP用户，我们将为你打六折进行收费");
            }
        }
        if (user == null) {
            model.addAttribute("bookcase", 0);
        } else {
            Bookcase bookcase = bookcaseDao.findByBookIdAndGroupId(bookId, user.getUserId());
            if (bookcase == null) {
                model.addAttribute("bookcase", 0);
            } else if (bookcase.getIsShow() == 0) {
                model.addAttribute("bookcase", 0);
            } else {
                model.addAttribute("bookcase", 1);
            }
        }
        Book book = bookDao.findById(bookId).get();
        int bookClicks = book.getBookClicks();
        book.setBookClicks(bookClicks + 1);
        List<BookLinkType> bookLinkTypes = bookLinkTypeDao.findByBookId(bookId);
        List<String> labels = new ArrayList<>();
        Long typeId = (long) 0;
        for (BookLinkType bookLinkType : bookLinkTypes
                ) {
            Type type = typeDao.findById(bookLinkType.getTypeId()).get();
            Long fatherId = type.getTypeParentId();
            if (fatherId != -1 && fatherId != 0) {
                typeId = bookLinkType.getTypeId();

            } else {
                labels.add(type.getTypeName());
            }
        }
        Type type = typeDao.findById(typeId).get();
        String subtype = type.getTypeName();
        Long fatherId = type.getTypeParentId();
        Type type1 = typeDao.findById(fatherId).get();
        String parentType = type1.getTypeName();
        bookDao.save(book);
        List<BookList> bookLists = bookListDao.findByBookIdOrderByBookListOrderAsc(bookId);
        if (book.getBookIsContract() == 0 || bookLists.size() <= 30) {  //判断本书的收费情况
            model.addAttribute("freebookLists", bookLists);
            model.addAttribute("free", "isfree");
        } else {
            model.addAttribute("freebookLists", bookLists.subList(0, 29));
            model.addAttribute("chargebookLists", bookLists.subList(30, bookLists.size()));
        }
        model.addAttribute("freeread", bookLists.get(0));
        model.addAttribute("parentype", parentType);
        model.addAttribute("subtype", subtype);
        model.addAttribute("book", book);
        model.addAttribute("labels", labels);
        model.addAttribute("chapter", bookListDao.countByBookId(book.getBookId()));

    }

    @Override
    public void updatesons(Long[] son, String[] sonName) {
        Type tempType = new Type();
        Type type = new Type();
        for (int i = 0; i < son.length; i++) {
            tempType = typeDao.findById(son[i]).get();
            if (sonName[i] == null || sonName[i] == "") {
                System.out.println();
                typeDao.deleteById(son[i]);
            } else {
                type.setTypeId(son[i]);
                type.setTypeName(sonName[i]);
                type.setTypeParentId(tempType.getTypeParentId());
                typeDao.save(type);
            }
        }
    }

    @Override
    public Result keyword(String keyWord) {
        List<String> keywords = bookService.getKeyWord(keyWord);
        for (String keword : keywords
                ) {
            System.out.println(keword);
        }
        List<String> keyword = new ArrayList<>();
        if (keywords.size() == 0) {
            return new Result(ResultCode.FAIL);
        }
        if (keywords.size() <= 10) {
            return new Result(ResultCode.SUCCESS, keywords);
        } else {
            return new Result(ResultCode.SUCCESS, keywords.subList(0, 9));

        }
    }

    @Override
    public List<Book> searchBook(String bookName) {
        List<Book> bookList = bookDao.findAllByBookNameContaining(bookName);
        List<Book> authorList = bookDao.findAllByAuthorNameContaining(bookName);
        bookList.addAll(authorList);
        List<Book> unique = bookList.stream().collect(
                Collectors.collectingAndThen(
                        toCollection(() -> new TreeSet<>(comparingLong(Book::getBookId))), ArrayList::new)
        );
        return unique;
    }

    @Override
    public List<Book> recommend(Long userId, List<Book> rankList) {//个性
        List<Long> bookIdList = bookcaseDao.getBooksId(userId, 1);
        List<Long> typeIdLists = new ArrayList<Long>();//把类型小list变为大list
        List<Long> fatherTypeId = new ArrayList<>(); //
        List<Long> typeIdList = new ArrayList<Long>();//存放查出类型的小list
        if (bookIdList == null) {
            return rankList.subList(0, 6);
        }
            for (Long bookId : bookIdList
                    ) {
                typeIdList = bookLinkTypeDao.getTypeIds(bookId);
                typeIdLists.addAll(typeIdList);
            }
            Type type = new Type();
            System.out.println(typeIdList.toString());
            for (Long typeId : typeIdLists
                    ) {
                type = typeDao.findByTypeIdAndTypeParentId(typeId, (long) 0);
                if (type!=null) {
                    fatherTypeId.add(type.getTypeId());
                }
            }
            Map<Long, Integer> map = new HashMap<Long, Integer>();//对重复的id进行计数
            for (Long item : fatherTypeId) {
                if (map.containsKey(item)) {
                    map.put(item, map.get(item).intValue() + 1);
                } else {
                    map.put(item, new Integer(1));
                }
            }
            Iterator<Long> keys = map.keySet().iterator();
            int max = -1;
            Long maxTypeId = (long) 0;
            while (keys.hasNext()) {
                Long key = keys.next();
                if (map.get(key).intValue() > max) {
                    max = map.get(key).intValue();
                }
            }
        Iterator<Long> keyse = map.keySet().iterator();
            while (keyse.hasNext()) {
                Long key = keyse.next();
                if (map.get(key).intValue() == max) {
                    maxTypeId = key;
                }
            }
            List<Book> currentListBook = new ArrayList<>();
            for (Long currentBookId : bookLinkTypeDao.getBookIds(maxTypeId)) {
                System.out.println("currentBookId"+currentBookId);
                currentListBook.add(bookDao.findById(currentBookId).get());
            }
            if (currentListBook.size() >= 7) {
                return currentListBook.subList(0, 6);
            }
            return currentListBook;
    }
    @Override
    public List<Book> finshedBook(){
        List<Book> bookList = bookDao.findAllByBookIsEnd(1);
        return bookList;
    }
    @CacheEvict(value = "finshBook", key = "1")
    @Override
    public void finshBook() {

    }
    @Cacheable(value = "finshBook",key="1")
    @Override
    public List<Book> unfinshedBook(){
        List<Book> bookList = bookDao.findAllByBookIsEnd(0);
        return bookList;
    }
    @CacheEvict(value = "unfinshBook", key = "1")
    @Override
    public void unfinshBook() {

    }
    @Cacheable(value = "unfreeBook",key = "1")
    @Override
    public List<Book> unfreeBook(){
        List<Book> bookList=bookDao.findAllByBookIsContract(1);
        return bookList;
    }
    @CacheEvict(value = "unfreeBook",key = "1")
    @Override
    public void unfreedBook() {

    }

    @Cacheable(value = "freeBook",key = "1")
    @Override
    public List<Book> freeBook(){
        List<Book> bookList=bookDao.findAllByBookIsContract(1);
        return bookList;
    }
    @CacheEvict(value = "freeBook",key = "1")
    @Override
    public void freedBook() {

    }

}